﻿using ezCloud.Api.Common;
using ezCloud.Api.Models;
using ezCloud.Data;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web.Http;

namespace ezCloud.Api.Controllers
{
    [AllowAnonymous]
    [RoutePrefix("api/EmailMarketing")]
    public class EmailMarketingController : ezController
    {
        public EmailMarketingController()
        {

        }
        #region Properties

        #endregion

        #region Config Email Methods
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("SaveConfigEmail")]
        public async Task<IHttpActionResult> SaveConfigEmail(ConfigEmailMarketingViewModels model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var currentClientUser = Common.UserUtitily.getUserProfile();
            try
            {
                if (model.HotelEmailConfigId.HasValue)
                {
                    var oldEmailConfig = context.HotelEmailConfig.Where(oh => oh.HotelEmailConfigId == model.HotelEmailConfigId && oh.HotelId == currentClientUser.HotelId).Single();
                    oldEmailConfig.ServerName = model.ServerName;
                    oldEmailConfig.Port = model.Port;
                    oldEmailConfig.PassEmail = model.PassEmail;
                    oldEmailConfig.UserName = model.UserName;
                    oldEmailConfig.HeaderHtml = model.HeaderHtml;
                    oldEmailConfig.FooterHtml = model.FooterHtml;
                    oldEmailConfig.EmailName = model.EmailName;
                    oldEmailConfig.EncryptionId = model.EncryptionId;
                }
                else
                {
                    HotelEmailConfig newEmailConfig = new HotelEmailConfig
                    {
                        ServerName = model.ServerName,
                        Port = model.Port,
                        PassEmail = model.PassEmail,
                        UserName = model.UserName,
                        HeaderHtml = model.HeaderHtml,
                        FooterHtml = model.FooterHtml,
                        EmailName = model.EmailName,
                        EncryptionId = model.EncryptionId,
                        HotelId = currentClientUser.HotelId
                    };
                    context.HotelEmailConfig.InsertOnSubmit(newEmailConfig);
                }
                context.SubmitChanges();
                await Notification.sendLogEmailMarketing(currentClientUser.UserName.ToLower(), currentClientUser.FullName + " submit config email marketing", currentClientUser.HotelId, "NOTIFICATION_EMAIL_MARKETING");
            }
            catch (Exception e)
            {
                await Notification.sendLogEmailMarketing(currentClientUser.UserName.ToLower(), "Error when " + currentClientUser.FullName + " submit config email marketing", currentClientUser.HotelId, "NOTIFICATION_EMAIL_MARKETING");
                return InternalServerError(e);
            }

            return Ok();
        }
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("GetConfigEmailById")]
        public async Task<IHttpActionResult> GetConfigEmailById(int configEmailId)
        {
            var currentClientUser = Common.UserUtitily.getUserProfile();
            var configEmail = context.HotelEmailConfig.Where(x => x.HotelEmailConfigId == configEmailId && x.HotelId == currentClientUser.HotelId).FirstOrDefault();
            return Ok(configEmail);
        }
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("GetAllConfigEmail")]
        public async Task<IHttpActionResult> GetAllConfigEmail()
        {
            var currentClientUser = Common.UserUtitily.getUserProfile();
            var listConfigEmail = context.HotelEmailConfig.Where(x => x.HotelId == currentClientUser.HotelId).ToList();
            return Ok(listConfigEmail);
        }
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("CheckConfigEmail")]
        [HttpGet]
        public async Task<IHttpActionResult> CheckConfigEmail(ConfigEmailMarketingViewModels model)
        {
            //if (!InternalServices.isAllowed()) { return BadRequest("IP_NOT_ALLOW_EXIST:" + HttpContext.Current.Request.UserHostAddress); };
            //string PmsUrl = WebConfigurationManager.AppSettings["RootUrl"];
            //subject = subject + "[" + PmsUrl + "]";
            //EmailSender.SendEmail(email, subject, content);
            try
            {
                MailMessage mail = new MailMessage();
                mail.To.Add(model.UserName);
                mail.From = new MailAddress(model.UserName);
                mail.Subject = model.EmailName;
                mail.Body = "Test config email";
                mail.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = model.ServerName;
                smtp.Port = model.Port;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new NetworkCredential(model.UserName, model.PassEmail);// Enter seders User name and password
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Send(mail);
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }

            return Ok();
        }
        #endregion
        #region Config template email methods
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("AddNewEmailTemplate")]
        public async Task<IHttpActionResult> AddNewEmailTemplate(HotelEmailTaskViewModels model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var currentClientUser = Common.UserUtitily.getUserProfile();
            HotelEmailTask newTemplate = new HotelEmailTask
            {
                HotelId = currentClientUser.HotelId,
                Body = model.Body,
                Day = model.Day,
                Status = model.Status,
                Subject = model.Subject,
                TypeId = model.TypeId,
                TypeStatus = model.TypeStatus,
                EmailCC = model.EmailCC,
                HotelEmailConfigId = model.HotelEmailConfigId
            };
            context.HotelEmailTask.InsertOnSubmit(newTemplate);
            context.SubmitChanges();

            await Notification.sendLogEmailMarketing(currentClientUser.UserName.ToLower(), currentClientUser.FullName + " submit new email template", currentClientUser.HotelId, "NOTIFICATION_EMAIL_MARKETING");
            return Ok();
        }
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("EditEmailTemplateByField")]
        public async Task<IHttpActionResult> EditEmailTemplateByField(int EmailTaskId, string fieldEdit, string valueEdit)
        {
            var currentClientUser = Common.UserUtitily.getUserProfile();
            var oldEmailTemplate = context.HotelEmailTask.Where(x => x.HotelEmailTaskId == EmailTaskId && x.HotelId == currentClientUser.HotelId).Single();
            switch (fieldEdit)
            {
                case "body":
                    oldEmailTemplate.Body = fieldEdit;
                    break;
                case "status":
                    int status;
                    if (Int32.TryParse(fieldEdit, out status))
                    {
                        oldEmailTemplate.Status = status;
                    }
                    else
                    {
                        return BadRequest(string.Format("Invalid input status {0}", fieldEdit));
                    }
                    break;
                case "day":
                    int day;
                    if (Int32.TryParse(fieldEdit, out day))
                    {
                        oldEmailTemplate.Day = day;
                    }
                    else
                    {
                        return BadRequest(string.Format("Invalid input day {0}", fieldEdit));
                    }
                    break;
                case "subject":
                    oldEmailTemplate.Subject = fieldEdit;
                    break;
                case "type":
                    int type;
                    if (Int32.TryParse(fieldEdit, out type))
                    {
                        oldEmailTemplate.TypeId = type;
                    }
                    else
                    {
                        return BadRequest(string.Format("Invalid input type {0}", fieldEdit));
                    }
                    break;
                case "typeStatus":
                    int typeStatus;
                    if (Int32.TryParse(fieldEdit, out typeStatus))
                    {
                        oldEmailTemplate.TypeStatus = typeStatus;
                    }
                    else
                    {
                        return BadRequest(string.Format("Invalid input typeStatus {0}", fieldEdit));
                    }
                    break;
                case "emailConfigId":
                    int emailConfigId;
                    if (Int32.TryParse(fieldEdit, out emailConfigId))
                    {
                        oldEmailTemplate.TypeStatus = emailConfigId;
                    }
                    else
                    {
                        return BadRequest(string.Format("Invalid input emailConfigId {0}", fieldEdit));
                    }
                    break;
                case "emailCC":
                    oldEmailTemplate.EmailCC = fieldEdit;
                    break;
                default:
                    break;
            }
            context.SubmitChanges();
            await Notification.sendLogEmailMarketing(currentClientUser.UserName.ToLower(), currentClientUser.FullName + " edit email template on " + fieldEdit, currentClientUser.HotelId, "NOTIFICATION_EMAIL_MARKETING");
            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("GetTemplateEmailById")]
        public async Task<IHttpActionResult> GetTemplateEmailById(int templateEmailId)
        {
            var currentClientUser = Common.UserUtitily.getUserProfile();
            var configEmail = context.HotelEmailTask.Where(x => x.HotelEmailTaskId == templateEmailId && x.HotelId == currentClientUser.HotelId).FirstOrDefault();
            return Ok(configEmail);
        }
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("GetAllTemplateEmail")]
        public async Task<IHttpActionResult> GetAllTemplateEmail()
        {
            var currentClientUser = Common.UserUtitily.getUserProfile();
            var listConfigEmail = context.HotelEmailTask.Where(x => x.HotelId == currentClientUser.HotelId).ToList();
            return Ok(listConfigEmail);
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("GetValueConfigTemplate")]
        public async Task<IHttpActionResult> GetValueConfigTemplate(string type)
        {
            Type qatype = null;
            switch (type)
            {
                case "hotels":
                    qatype = typeof(Data.Enum.Hotels);
                    break;
                case "guest":
                    qatype = typeof(Data.Enum.Guests);
                    break;
                case "booking":
                    qatype = typeof(Data.Enum.BookingInformation);
                    break;
                case "general":
                    qatype = typeof(Data.Enum.General);
                    break;
                default:
                    break;
            }
            string[] names = qatype.GetEnumNames();

            List<string> listNameEnum = Enum.GetNames(qatype).ToList();
            string valueConfig = string.Join("; ", listNameEnum.Select(x => "{" + x + "}"));
            return Ok();
        }
        #endregion
        #region Helper methods
        #endregion
    }
}
